package fr.unice.servlet;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gdata.client.Query;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.Category;
import com.google.gdata.data.Link;
import com.google.gdata.data.media.mediarss.MediaThumbnail;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;

import fr.unice.outils.Panier;
import fr.unice.outils.PanierBean;

@SuppressWarnings("serial")
public class PanierServlet extends HttpServlet {

        private ArrayList<Panier> lesPaniers = new ArrayList<Panier>();

        public void init() {
        }

        /**
         * The URL of the "Videos" feed
         */
        public static final String VIDEOS_FEED = "http://gdata.youtube.com/feeds/api/videos";

        public void doGet(HttpServletRequest req, HttpServletResponse rep) {
                try {

                        String uneVideo = null;

                        Panier panierUser = null;
                        PanierBean panier = (PanierBean) this.getServletContext()
                                        .getAttribute("panier");
                        /*
                         * si on a le parametre video dans la requette on teste la validit
                         * et on ajoute la video au panier
                         */

                        if (req.getParameter("video") != null) {
                                uneVideo = (String) req.getParameter("video");

                                panierUser = new Panier(panier.getLesTag(), panier
                                                .getTagSelection(), panier.getTagCpt(), panier
                                                .getVideoList(), panier.getSuggestion());
                                YouTubeService myService = new YouTubeService(
                                                "ytapi-CedricDebeaume-acb-2ldn3hca-0",
                                                "AI39si4hrTZVAAS1IOV90AWq5oK3M88DvnolhRxJenj7Nly2J4NCwXXs0zXwoF-U6rO3jn9hQvZl_qcK4HNGCINo6Qpbn_ZYdQ");
                                YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));
                                query.setVideoQuery(uneVideo);
                                VideoFeed videoFeed = myService.query(query, VideoFeed.class);
                                for (VideoEntry ve : videoFeed.getEntries()) {
                                        panierUser.addVideo(ve);
                                }
                                majSuggestion(myService, panierUser);

                        }

                        if (req.getParameter("delvideo") != null) {
                                uneVideo = (String) req.getParameter("delvideo");

                                panierUser = new Panier(panier.getLesTag(), panier
                                                .getTagSelection(), panier.getTagCpt(), panier
                                                .getVideoList(), panier.getSuggestion());
                                YouTubeService myService = new YouTubeService(
                                                "ytapi-CedricDebeaume-acb-2ldn3hca-0",
                                                "AI39si4hrTZVAAS1IOV90AWq5oK3M88DvnolhRxJenj7Nly2J4NCwXXs0zXwoF-U6rO3jn9hQvZl_qcK4HNGCINo6Qpbn_ZYdQ");
                                YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));
                                query.setVideoQuery(uneVideo);
                                VideoFeed videoFeed = myService.query(query, VideoFeed.class);
                                for (VideoEntry ve : videoFeed.getEntries()) {
                                        panierUser.deleteVideo(ve);
                                }
                                majSuggestion(myService, panierUser);

                        }


                        if (req.getParameter("clean") != null) {
                                String param = (String) req.getParameter("clean");
                                panierUser = new Panier(panier.getLesTag(), panier
                                                .getTagSelection(), panier.getTagCpt(), panier
                                                .getVideoList(), panier.getSuggestion());
                                YouTubeService myService = new YouTubeService(
                                                "ytapi-CedricDebeaume-acb-2ldn3hca-0",
                                                "AI39si4hrTZVAAS1IOV90AWq5oK3M88DvnolhRxJenj7Nly2J4NCwXXs0zXwoF-U6rO3jn9hQvZl_qcK4HNGCINo6Qpbn_ZYdQ");
                                YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED));
                                query.setVideoQuery(uneVideo);
                                panierUser.cleanPanier();
                                majSuggestion(myService, panierUser);

                        }


                        String reponse = "";
                        //reponse +="##panier";
                        reponse += "<h3>Mon panier";
                        reponse+="&nbsp;<input type='button' id='vider' value='Vider' onclick='clean();' /></h3>";
                        reponse +="<a href='Recap'>Graphiques des utilisateurs</a><br/>";
                        reponse += "<div id=\"blockpanier\">";
//                      reponse +="<rep>";
//                      reponse+="<root>";
                        // preparation de la reponse xml pour le panier
                        ArrayList<VideoEntry> pan = panierUser.getVideoList();
                        if (pan.size() > 0) {


                                reponse+="<table id=\"tabpanier\">";
                                int compteur = 0;
                                for (int j = 0; j < pan.size(); j++) {
                                        YouTubeMediaGroup mediaGroup = pan.get(j).getMediaGroup();
                                        List<MediaThumbnail> liste = mediaGroup.getThumbnails();
                                        reponse +="<tr><td width=\"20%\">";
                                        //reponse += "<div class=\"video\">";
                                        reponse += "<a href=\""
                                                        + pan.get(j).getHtmlLink().getHref()
                                                        + "\"><img src=\"" + liste.get(0).getUrl()
                                                        + "\"/></a>";
                                        reponse +="</td><td>";
                                        //reponse += "<div class=\"infovideo\">";
                                        if (pan.get(j).getTitle() != null) {
                                                String titre = pan.get(j).getTitle().getPlainText();
                                                int longeurTitreSouhaite = 25;
                                                if(titre.length()> longeurTitreSouhaite){
                                                        String titreAbreg = titre.substring(0, longeurTitreSouhaite);
                                                        titreAbreg += "...";
                                                        reponse += "<span class=\"soustitre\" ><a href=\""+pan.get(j).getHtmlLink().getHref()+"\" title="+titre+">" + titreAbreg+"</a></span>";
                                                }
                                                else{
                                                        reponse += "<span class=\"soustitre\" ><a href=\""+pan.get(j).getHtmlLink().getHref()+"\" title="+titre+">" + titre+"</a></span>";
                                                }
                                        }

                                        try{
                                                //affiche le nombre de fois que la video a ete vue
                                                reponse +="<br/>Vues: " + pan.get(j).getStatistics().getViewCount();


                                                //affiche la duree de la video
                                                long dureeSec = mediaGroup.getDuration();
                                                long dureeMin = dureeSec/60;
                                                long dureeSecRestante = dureeSec%60;
                                                if(dureeSecRestante<=9)
                                                        reponse +="<br/><b>" + dureeMin+":0"+dureeSecRestante+"</b>";
                                                else
                                                        reponse +="<br/><b>" + dureeMin+":"+dureeSecRestante+"</b>";
                                        }
                                        catch(Exception e){
                                        }


                                        String nom = pan.get(j).getHtmlLink().getHref();
                                        Scanner scanner = new Scanner(nom);
                                        scanner.useDelimiter("v=");
                                        String adr = scanner.next();
                                        String nomVideo = scanner.next();
                                        //reponse += "<br/>" + nomVideo;
                                        reponse += "&nbsp;<input type='checkbox' onclick='delPanier(\""
                                                        + nomVideo + "\");'/>Supprimer du panier ";
                                        //reponse += "</div>";
                                        //reponse += "</div>";
                                        reponse +="</td></tr>";
                                        compteur++;
                                        if (compteur > 10)
                                                break;
                                }
                                reponse +="</table>";
                                reponse += "</div><!-- fin div block panier-->";

                                // preparation de la reponse xml pour les suggestions
                                //reponse += "##suggestions";
                                reponse +="<h3>Mes suggestions</h3>";
                                reponse += "<div id=\"blocksuggestions\">";
                                ArrayList<VideoEntry> suggestions = panierUser.getSuggestion();
                                if (suggestions.size() > 1) {
                                        reponse+="<table id=\"tabpanier\">";
                                        int cpt = 0;
                                        for (int j = 0; j < suggestions.size(); j++) {
                                                YouTubeMediaGroup mediaGroup = suggestions.get(j)
                                                                .getMediaGroup();

                                                List<MediaThumbnail> liste = mediaGroup.getThumbnails();
                                                reponse+="<tr><td width=\"20%\">";
                                                //reponse += "<div class=\"video\">";
                                                reponse += "<a href=\""
                                                                + suggestions.get(j).getHtmlLink().getHref()
                                                                + "\"><img src=\"" + liste.get(0).getUrl()
                                                                + "\"/></a>";
                                                reponse +="</td><td>";
                                                //reponse += "<div class=\"infovideo\">";
                                                if (suggestions.get(j).getTitle() != null) {
                                                        String titre = suggestions.get(j).getTitle().getPlainText();
                                                        int longeurTitreSouhaite = 25;
                                                        if(titre.length()> longeurTitreSouhaite){
                                                                String titreAbreg = titre.substring(0, longeurTitreSouhaite);
                                                                titreAbreg += "...";
                                                                reponse += "<a href=\""+suggestions.get(j).getHtmlLink().getHref()+"\" title="+titre+">" + titreAbreg+"</a>";
                                                        }
                                                        else{
                                                                reponse += "<a href=\""+suggestions.get(j).getHtmlLink().getHref()+"\" title="+titre+">" + titre+"</a>";
                                                        }
                                                }

                                                try{
                                                        //affiche le nombre de fois que la video a ete vue
                                                        reponse +="<br/>Vues: " + suggestions.get(j).getStatistics().getViewCount();


                                                        //affiche la duree de la video
                                                        long dureeSec = mediaGroup.getDuration();
                                                        long dureeMin = dureeSec/60;
                                                        long dureeSecRestante = dureeSec%60;
                                                        if(dureeSecRestante<=9)
                                                                reponse +="<br/><b>" + dureeMin+":0"+dureeSecRestante+"</b>";
                                                        else
                                                                reponse +="<br/><b>" + dureeMin+":"+dureeSecRestante+"</b>";
                                                }
                                                catch(Exception e){
                                                }

                                                String nom = suggestions.get(j).getHtmlLink().getHref();
                                                Scanner scanner = new Scanner(nom);
                                                scanner.useDelimiter("v=");
                                                String adr = scanner.next();
                                                String nomVideo = scanner.next();
                                                //reponse += "<br/>" + nomVideo;
                                                reponse += "&nbsp;<input type='checkbox' onclick='addPanier(\""
                                                                + nomVideo + "\");'/>Ajouter au panier ";
                                                //reponse += "</div>";
                                                //reponse += "</div>";
                                                reponse +="</td></tr>";

                                                // List<MediaThumbnail> thumb =
                                                // mediaGroup.getThumbnails();
                                                // reponse+="<suggestion>";
                                                // reponse+="<image>";
                                                // reponse+=thumb.get(1).getUrl();
                                                // reponse+="</image>";
                                                // reponse+="<url>";
                                                // reponse+=suggestions.get(j).getHtmlLink().getHref();
                                                // reponse+="</url>";
                                                // reponse+="<title>";
                                                // reponse+=suggestions.get(j).getTitle().getPlainText();
                                                // reponse+="</title>";
                                                // reponse+="</suggestion>";

                                                cpt++;
                                                if (cpt > 10)
                                                        break;
                                        }
                                        reponse +="</table>";
                                        reponse += "</div><!-- fin blocksuggestion--> ";
                                }
                                // rep.sendRedirect("panier.jsp");
//                              reponse +="</rep>";
                                rep.setContentType("text/xml;charset=UTF-8");
                                rep.setHeader("Cache-Control", "no-cache");
                                rep.getWriter().write(reponse);


                        }else{
                        //reponse += "##suggestionsMES SUGGESTIONS";
                        rep.setContentType("text/xml;charset=UTF-8");
                        rep.setHeader("Cache-Control", "no-cache");
                        rep.getWriter().write(reponse);
                        }

                } catch (Exception e) {
                }
        }

        public void majSuggestion(YouTubeService myService, Panier panierUser) {
                ArrayList<String> tagSelection = panierUser.getTagSelection();
                panierUser.cleanSuggestion();
                try {
                        // si on a + d'1 tag on peut faire la recherche sur les tags
                        if (tagSelection.size() > 1) {
                                String tagrq = "";
                                for (int i = 0; i < tagSelection.size(); i++) {
                                        if (i == 0)
                                                tagrq = tagSelection.get(i);
                                        else
                                                tagrq = tagrq + "+" + tagSelection.get(i);
                                }
                                YouTubeQuery query = new YouTubeQuery(new URL(VIDEOS_FEED
                                                + "?vq=" + tagrq));

                                VideoFeed suggestionFeed = myService.query(query,
                                                VideoFeed.class);
                                panierUser.cleanSuggestion();

                                for (VideoEntry ve : suggestionFeed.getEntries()) {
                                        panierUser.addSuggestion(ve);
                                }

                                // sinon on utilise la recherche similaire de google
                        } else {

                                /*
                                 * a faire
                                 */
                                // essayer de faire les suggestion a partir d'une video
                        }
                } catch (Exception e) {
                }
        }

}
